<?php
/*
    OpenLib
    Copyright (C) 2011  Michael Gukov, Pham Thi Thuy Duong

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/


namespace Sun;

abstract class Application implements IApplication {
    protected $conf;
    protected $front_controller;
    protected $error_controller;
    private $request;

    public function __construct() {
        $this->conf = parse_ini_file(Sun::appPath()."/app/config/config.ini", true);
        Sun::setAppConfig($this->conf);

        $this->front_controller = $this->conf['app']['front_controller'];
        $this->error_controller = $this->conf['app']['error_controller'];
    }

    public function Request() { return $this->request; }

    public function Run() {
        $this->request = new Request();
        $u = $this->request->u;
        if (count($u) == 0) $u[] = $this->front_controller;
        $this->Manage($u);
    }

    protected function Manage($u) {
        $class = "\\App\\Controllers\\".ucfirst($u[0]);
        try {
            $controller = new $class();
            //$controller->Action($this->request, @$u[1]);
        } catch (Exceptions\NotFound $e) {
            $class = "\\App\\Controllers\\".$this->error_controller;
            $controller = new $class();
            $controller->Action($this->request, $u);
            return;
        }
        $controller->Action($this->request, @$u[1]);
    }
}
